package com.newlink.building

import android.app.Application
import android.app.Notification
import android.app.NotificationChannel
import android.app.NotificationManager
import android.content.Context
import android.graphics.Color
import android.media.RingtoneManager
import android.os.Build
import android.os.Handler
import android.os.Looper
import com.alibaba.sdk.android.push.CloudPushService
import com.alibaba.sdk.android.push.CommonCallback
import com.alibaba.sdk.android.push.PushControlService
import com.alibaba.sdk.android.push.huawei.HuaWeiRegister
import com.alibaba.sdk.android.push.impl.XiaoMiMsgParseImpl
import com.alibaba.sdk.android.push.noonesdk.PushServiceFactory
import com.alibaba.sdk.android.push.register.GcmRegister
import com.alibaba.sdk.android.push.register.ThirdPushManager
import com.newlink.building.common_base.constant.Base_Constant
import com.newlink.building.common_base.utils.Base_ConfigHelper
import com.newlink.building.common_base.utils.Base_CrashHandler
import com.newlink.building.common_base.utils.LogHandlerThread
import com.newlink.building.common_base.utils.NetWorkUtil
import com.newlink.building.common_base.utils.logDebug
import com.newlink.building.library_rino.LoopBackManager
import com.newlink.building.manager.Module_Phone_VoipController
import com.newlink.building.push.MessageIntentService
import com.newlink.building.utils.NL_PushServiceHelper
import kotlin.properties.Delegates

/**
 * Created by xiaodong on 2022/7/25.
 */
class App : NL_App() {

    companion object {
        var context: Context by Delegates.notNull()
            private set

        lateinit var instance: Application

        // 通过变量判断应用是否处于前台
        private var runningActivities = 0
    }

    private val handler = Handler(Looper.getMainLooper())

    override fun onCreate() {

        super.onCreate()

        context = applicationContext
        LoopBackManager.required(this).nativeLbInit(Base_Constant.NETWORK_LISTEN_PORT)
        Module_Phone_VoipController.required(this)
        LogHandlerThread.instance?.initHanderThead()
        initCloudChannel(this)
        checkConnectionStatus()
        createNotificationChannel(this)
        val crashHandler = Base_CrashHandler.getInstance(context)
        crashHandler?.init()
    }

    private fun checkConnectionStatus() {
        val controlService = PushServiceFactory.getPushControlService()
        controlService.setConnectionChangeListener(object :
                PushControlService.ConnectionChangeListener {
                override fun onConnect() {
                    logDebug<App>("[PushService] onConnect...")
                }

                override fun onDisconnect(code: String, msg: String) {
                    val isNetworkIssue = !NetWorkUtil.isNetworkConnected(applicationContext)
                    // 过一段时间再检查，比如30s
                    handler.postDelayed(
                        {
                            logDebug<App>("[PushService] onDisconnect  isNetworkIssue:$isNetworkIssue isConnected:${controlService.isConnected}")
                            if (NetWorkUtil.isNetworkConnected(applicationContext) && !controlService.isConnected) {
                                // 如果网络没有问题，而且连接没有恢复
                                // 此时记录埋点 code 和 msg 信息，一定要记录msg信息
                                recordDisconnectEvent(code, msg)
                                if (isNetworkIssue) {
                                    logDebug<App>("[PushService] reconnect...")
                                    // 刚才没有网络，尝试重连
                                    controlService.reconnect()
                                } else {
                                    logDebug<App>("[PushService] reset and initCloudChannel")
                                    // 网络没有问题，或者重连也不行，进行重置，重新进行初始化
                                    controlService.reset()
                                    initCloudChannel(context)
                                }
                            }
                        },
                        30 * 1000
                    )
                }
            })
    }

    private fun recordDisconnectEvent(code: String, msg: String) {
        val logMessage = "Disconnect code: $code, msg: $msg"
        LogHandlerThread.instance?.writeLog(context, "[PushService]", logMessage)
        logDebug<App>("[PushService] recordDisconnectEvent  $logMessage")
    }

    fun logout() {
        PushServiceFactory.getCloudPushService().turnOffPushChannel(object : CommonCallback {
            override fun onSuccess(p0: String?) {
                logDebug<App>("[PushService] >>>> turnOffPushChannel success")
            }

            override fun onFailed(p0: String?, p1: String?) {
                logDebug<App>("[PushService] >>>> turnOffPushChannel onFailed")
            }
        })
    }

    fun login() {
        PushServiceFactory.getCloudPushService().turnOnPushChannel(object : CommonCallback {
            override fun onSuccess(s: String) {
                logDebug<App>("[PushService] >>>> Turn on push channel success")
            }

            override fun onFailed(errorCode: String, errorMessage: String) {
                logDebug<App>(
                    "[PushService] >>>> Turn on push channel failed, errorCode: $errorCode, errorMessage: $errorMessage"
                )
            }
        })
    }

    // 初始化阿里云推送通知服务
    private fun initCloudChannel(applicationContext: Context) {
        logDebug<App>("initCloudChannel")

        // 从配置文件读取参数
        val emasConfig = Base_ConfigHelper.getEmasConfig(applicationContext)
        val googleConfig = Base_ConfigHelper.getGoogleServicesConfig(applicationContext)

        if (emasConfig == null || googleConfig == null) {
            logDebug<App>("[App] Configuration files are missing or invalid")
            logDebug<App>(Base_ConfigHelper.getConfigDiagnosticInfo(applicationContext))
            return
        }

        // 使用配置文件中的参数初始化阿里云推送
        PushServiceFactory.init(
            applicationContext,
            emasConfig.appKey,
            emasConfig.appSecret,
            true
        )

        // 使用配置文件中的参数注册 GCM/FCM 辅助通道
        try {
            GcmRegister.register(
                this,
                googleConfig.projectNumber,
                googleConfig.mobilesdkAppId,
                googleConfig.projectId,
                googleConfig.apiKey
            )
            logDebug<App>("[App] FCM registration successful")
        } catch (e: Exception) {
            // Firebase 服务不可用（通常在中国大陆），使用阿里云推送作为主要通道
            logDebug<App>("[App] FCM not available (expected in mainland China), using Aliyun Push only: ${e.message}")
        }

        logDebug<App>("[App] Initialized with config - EMAS AppKey: ${emasConfig.appKey}, Google Project: ${googleConfig.projectId}")

        val pushService = PushServiceFactory.getCloudPushService()
        pushService.setLogLevel(CloudPushService.LOG_DEBUG) // 仅适用于Debug包，正式包不需要此行

        // 使用 PushServiceHelper 进行推送服务检查和注册
        NL_PushServiceHelper.checkPushChannelStatus(applicationContext)
        NL_PushServiceHelper.registerPushService(applicationContext)
        // 设置 MessageIntentService
        pushService.setPushIntentService(MessageIntentService::class.java)
        // 华为通道
        val huaWeiRegister = HuaWeiRegister.register(this)
        // 小米
        ThirdPushManager.registerImpl(XiaoMiMsgParseImpl())

        // 获取设备ID，使用兜底方案
        val deviceId = NL_PushServiceHelper.getDeviceId(this)
        logDebug<App>("[push service] DeviceId: $deviceId")

        // 打印诊断信息
        logDebug<App>(NL_PushServiceHelper.getDiagnosticInfo(this))
    }

    // 创建一个推送通知通道
    private fun createNotificationChannel(app: Application) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            val mNotificationManager =
                app.getSystemService(NOTIFICATION_SERVICE) as NotificationManager
            // 通知通道的id
            val id = getString(R.string.push_notification_channel_id)
            // 用户可以看到的通知通道的名字.
            val name: CharSequence = getString(
                R.string.push_notification_channel_name,
                context.getString(R.string.app_name_smart)
            )
            // 用户可以看到的通知通道的描述
            val description = getString(
                R.string.push_notification_channel_name,
                context.getString(R.string.app_name_smart)
            )
            val importance = NotificationManager.IMPORTANCE_DEFAULT
            val mChannel = NotificationChannel(id, name, importance)
            // 配置通知渠道的属性
            mChannel.description = description
            // 设置通知出现时的闪灯（如果 android 设备支持的话）
            mChannel.enableLights(true)
            mChannel.lightColor = Color.RED
            // 设置通知出现时的震动（如果 android 设备支持的话）
            mChannel.enableVibration(true)
            mChannel.setSound(
                RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION),
                Notification.AUDIO_ATTRIBUTES_DEFAULT
            )
//            mChannel.setSound(null, null)
            mChannel.vibrationPattern = longArrayOf(100, 200, 300, 400, 500, 400, 300, 200, 400)
            // 最后在notificationmanager中创建该通知渠道
            mNotificationManager.createNotificationChannel(mChannel)
        }
    }
}
